import { designComponents } from 'src/use/designComponents';
import { DefineComponent, defineComponent, markRaw, reactive, watch } from 'vue';
import { AppNavigator } from './app-navigator';

/**
 * markRaw是什么？
 * DefineComponent是什么类型
 */

export const AppNavigatorPage = designComponents({
  setup: () => {
    const state = reactive({
      PageComponent: null as null | DefineComponent,
    });

    // 注入navigator
    const navigator = AppNavigator.use.inject();

    const utils = {
      reset: async () => {
        let { path } = navigator.state.route;
        if (!path) return;
        if (path.charAt(0) === '/') {
          path = path.slice(1);
        }
        // 根据路由自动加载对应组件
        const Component = (await import('story/pages/' + path)).default;
        state.PageComponent = markRaw(Component);
      },
    };
    // 监听路由path，更改后执行 reset方法
    watch(() => navigator.state.route.path, utils.reset, { immediate: true });

    return {
      render: () => {
        const { PageComponent } = state;
        return <div class="app-navigator-page">{!!PageComponent ? <PageComponent /> : null}</div>;
      },
    };
  },
});
